﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Q7.BevTree
{
    public class BevNodePrioritySelector : BevNode
    {
        protected int _currentSelectedIndex = -1;
        protected int _lastSelectedIndex = -1;

        public BevNodePrioritySelector(string debugName)
            : base(debugName)
        {
        }

        protected override bool DoEvaluate(BevNodeInputParam input)
        {
            _currentSelectedIndex = -1;

            var len = Children.Count;
            for (var i = 0; i < len; ++i)
            {
                if (Children[i].Evaluate(input))
                {
                    _currentSelectedIndex = i;
                    return true;
                }
            }
            return false;
        }

        protected override void DoTransition(BevNodeInputParam input)
        {
            if (CheckIndex(_lastSelectedIndex))
            {
                Children[_lastSelectedIndex].Transition(input);
            }
            _lastSelectedIndex = -1;
        }

        protected override int DoTick(BevNodeInputParam input, BevNodeOutputParam output)
        {
            int isFinish = BRS_FINISH;

            if (CheckIndex(_currentSelectedIndex))
            {
                if (_currentSelectedIndex != _lastSelectedIndex)
                {
                    if (CheckIndex(_lastSelectedIndex))
                    {
                        Children[_lastSelectedIndex].Transition(input);
                    }

                    _lastSelectedIndex = _currentSelectedIndex;
                }
            }

            if (CheckIndex(_lastSelectedIndex))
            {
                isFinish = Children[_lastSelectedIndex].Tick(input, output);
                if (isFinish == BRS_FINISH)
                    _lastSelectedIndex = -1;
            }

            return isFinish;
        }
    }
}
